﻿

namespace ModularAndPlugin.Core.IOC.ServiceLocation
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.Composition.Hosting;
    using System.ComponentModel.Composition.Primitives;
    using System.Linq;

    /// <summary>
    /// 自定义导出.
    /// </summary>
    public class CustomExportProvider : ExportProvider
    {


        #region Methods
        /// <summary>
        /// Gets all exports for this provider.
        /// </summary>
        /// <param name="definition">The import definition to match.</param>
        /// <param name="atomicComposition">The atomic composition.</param>
        /// <returns>An enumerable of available exports.</returns>
        protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition)
        {
            string typeName = GetTypeName(definition.ContractName);
            if (ObjectContainer.IsHas(typeName))///todo:此处处理可能有不妥，后续完善
            {
                var export = new Export(definition.ContractName,
                    () => ObjectContainer.GetObject(typeName));
                return new List<Export> { export };
            }
            return Enumerable.Empty<Export>();
        }


        private string GetTypeName(string ConTractName)
        {
            int indx = ConTractName.LastIndexOf('.');
            indx = Math.Max(0, indx);
            string typeName = ConTractName;
            typeName = typeName.Substring(indx + 1, typeName.Length - indx - 1);
            return typeName;
        }

        #endregion
    }
}
